<?php
class CSession_Mysql {
	private $lifetime = 1800;
	private $db;
	
	function __construct(){
		$this->db = new Session_Model();
		$this->lifetime = RonBase::load_config('system','session_ttl');
		session_set_save_handler(array(&$this,'open'), array(&$this,'close'), array(&$this,'read'), array(&$this,'write'), array(&$this,'destroy'), array(&$this,'gc'));
    	session_start();
	}
	
	public function open($save_path, $session_name){
		return true;
	}
	
	public function close(){
		return $this->gc($this->lifetime);
	}
	
	public function read($id){
		$r = $this->db->get_one(array('sessionid'=>$id), 'data');
		return $r ? $r['data'] : '';
	}
	
	public function write($id, $data){
		$uid = isset($_SESSION['userid']) ? $_SESSION['userid'] : '';
		$roleid = isset($_SESSION['roleid']) ? $_SESSION['roleid'] : 0;
		$m = defined('ROUTE_M') ? ROUTE_M : '';
		$c = defined('ROUTE_C') ? ROUTE_C : '';
		$a = defined('ROUTE_A') ? ROUTE_A : '';
		if(strlen($data) > 255) $data = '';
		$system = new CSysfunction();
		$ip = $system->get_ip();
		$sessiondata = array(
			'sessionid' => $id,
			'userid' => $uid,
			'ip' => $ip,
			'lastvisit' => SYS_TIME,
			'roleid'=>$roleid,
			'm'=>$m,
			'c'=>$c,
			'a'=>$a,
			'data'=>$data,		
		);
		return $this->db->insert($sessiondata,1,1);
	}
	
	public function destroy($id){
		return $this->db->delete(array('sessionid'=>$id));
	}
	
	public function gc($maxlifetime){
		$expiretime = SYS_TIME - $maxlifetime;
		return $this->db->delete("`lastvisit`<$expiretime");
	}
}